<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>订单列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row class="query">
        <el-col :span="24">
          <el-date-picker v-model="rangedDate"
            type="daterange"xs
            value-format='yyyy-MM-dd'
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
          <el-select v-model="searchData.js" placeholder="请选择结算方式" clearable popper-class="dropdownbox" filterable style="margin-left: 10px;width: 200px;">
            <el-option v-for="element in jsList"
              :label="element.label"
              :value="element.value">
              <span>{{ element.label }}</span>
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-input placeholder="请输入客户名查询"
            v-model="searchData.customer"
            clearable style="width: 200px;">
          </el-input>
          <el-input placeholder="请输入规格查询"
            v-model="searchData.model"
            clearable style="margin-left: 10px;width: 200px;">
          </el-input>
          <el-button type="primary" @click="search" style="margin-left: 10px;">查询</el-button>
          <el-button @click="clear" style="margin-left: 10px;">重置</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="1.5">
          <el-button type="success" @click="goAddPage()" v-if="role !==5" style="margin-top: 10px;">添加订单</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="orderList"
        row-key="index"
        lazy
        :load="load"
        :default-expand-all="expandAll"
        border
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        :row-class-name="tableRowClassName">
        <el-table-column label="日期" prop="date" min-width="160" align="center" fixed="left"></el-table-column>
        <el-table-column label="ID" prop="oid" width="75" align="center" fixed="left"></el-table-column>
        <el-table-column label="客户名称" prop="customer" align="center" min-width="160" fixed="left"></el-table-column>
        <el-table-column label="发票" prop="invoice" width="50" align="center"></el-table-column>
        <el-table-column label="含税" prop="tax" width="50" align="center"></el-table-column>
        <el-table-column label="发货" prop="send" width="70" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.children">
              <div v-if="role === 1 || role === 3">
                <el-button type="danger" icon="el-icon-close" size="mini" circle @click="openBox(scope.row.order_id, 1)" v-if="scope.row.send == 0" :disabled="scope.row.resource ? true: false"></el-button>
                <el-button type="success" icon="el-icon-check" size="mini" circle @click="openBox(scope.row.order_id, 0)" v-if="scope.row.send == 1" :disabled="scope.row.resource ? true: false"></el-button>
              </div>
              <div v-else>
                <el-button type="danger" icon="el-icon-close" size="mini" circle disabled v-if="scope.row.send === 0"></el-button>
                <el-button type="success" icon="el-icon-check" size="mini" circle disabled v-if="scope.row.send !== 0"></el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="安装日期" prop="installtime" min-width="135" align="center"></el-table-column>
        <el-table-column label="发货确认时间" prop="sendtime" min-width="125" align="center"></el-table-column>
        <el-table-column label="类别" prop="product" align="center" min-width="85"></el-table-column>
        <el-table-column label="产品名称" prop="productn" align="center" min-width="160"></el-table-column>
        <el-table-column label="规格" prop="model" align="center" min-width="160"></el-table-column>
        <el-table-column label="新旧" prop="new" width="50" align="center"></el-table-column>
        <el-table-column label="单价" prop="price" min-width="110" align="center"></el-table-column>
        <el-table-column label="成本" prop="cost" min-width="110" align="center" v-if="role === 1 || role === 3 || role === 4"></el-table-column>
        <el-table-column label="数量" prop="amoumt" align="center" min-width="100"></el-table-column>
        <el-table-column label="折扣" prop="discount" align="center" min-width="100"></el-table-column>
        <el-table-column label="总价" prop="tprice" min-width="120" align="center"></el-table-column>
        <el-table-column label="利润" prop="profits" align="center" min-width="120" v-if="role === 1 || role === 3 || role === 4"></el-table-column>
        <el-table-column label="实收" prop="paid" align="center" min-width="120"></el-table-column>
        <el-table-column label="应收" prop="npaid" align="center" min-width="120"></el-table-column>
        <el-table-column label="结算方式" prop="js" min-width="105" align="center"></el-table-column>
        <el-table-column label="已回款" prop="is_repayment" width="70" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.product === '合计'">
              <el-button type="danger" icon="el-icon-close" size="mini" circle @click="repayment(scope.row.oid, 1)" v-if="scope.row.is_repayment === 0"></el-button>
              <el-button type="success" icon="el-icon-check" size="mini" circle @click="repayment(scope.row.oid, 2)" v-if="scope.row.is_repayment === 1"></el-button>
            </div>
            <div v-else-if="scope.row.product !== '合计'">
              <el-button type="danger" icon="el-icon-close" size="mini" circle @click="repayment(scope.row.id, 3)" v-if="scope.row.is_repayment === 0"></el-button>
              <el-button type="success" icon="el-icon-check" size="mini" circle @click="repayment(scope.row.id, 4)" v-if="scope.row.is_repayment === 1"></el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="170" fixed="right" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.product === '合计'">
              <el-button size="mini" type="info" @click="handlePrint(scope.row.order_id)">打印</el-button>
              <el-button size="mini" type="primary" @click="handleDetail(scope.row.order_id)">详情</el-button>
              <el-button size="mini" type="success" @click="handleSave(scope.row.order_id)" v-if="!scope.row.send && role !== 5" style="margin-top: 2px;">添加</el-button>
            </div>
            <div v-else-if="scope.row.product !== '合计'">
              <el-button size="mini" type="warning" @click="handleEdit(scope.row.id)" v-if="!scope.row.send && role !== 5">编辑</el-button>
              <el-button size="mini" type="warning" @click="handleEditSerial(scope.row.id)" v-else-if="role === 5">编辑序列号</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)" v-if="(!scope.row.send || scope.row.resource) && role !== 5">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pager.currPage"
        :page-sizes="[1, 3, 5, 10]"
        :page-size="pager.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pager.totalRecord">
      </el-pagination>
      <el-dialog title="编辑序列号" :visible.sync="editSerialDialog" :before-close="handleSerialClose" label-width="110px">
        <el-form :model="serialList" ref="serialForm">
          <el-row>
            <el-col :span="8">
              <el-form-item label="日期" prop="date">
                <el-date-picker type="date" placeholder="选择日期" v-model="serialList.date" value-format='yyyy-MM-dd' readonly>
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户名称" prop="customer">
                <el-input v-model="serialList.customer" readonly style="width:200px"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="名称" prop="productn">
                <el-input v-model="serialList.productn" readonly style="width:200px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="型号" prop="model">
                <el-input v-model="serialList.model" readonly style="width:200px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="数量" prop="amoumt">
                <el-input v-model="serialList.amoumt" readonly style="width:200px"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-button type="success" @click="addSerial" style="margin-top: 10px;">新增序列号</el-button>
        <el-table :data="serialList.serial">
          <el-table-column type="index" width="50"></el-table-column>
          <el-table-column label="序列号" prop="serial_number" align="center">
            <template slot-scope="scope">
              <el-input v-model="serialList.serial[scope.$index].serial_number" style="width:300px"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right" align="center">
            <template slot-scope="scope">
              <el-button type="danger" @click.native.prevent="deleteSerial(scope.$index, serialList.serial)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editSerialDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitSerial">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      role: '',
      loading: true,
      rangedDate: null,
      expandAll: false,
      searchData: {
        start_date: '',
        end_date: '',
        customer: '',
        model: '',
        js: ''
      },
      pager: {
        currPage: 1,
        pageSize: 10,
        totalRecord: 0
      },
      orderList: [],
      jsList: [
        {
          label: '赊销',
          value: '赊销'
        },
        {
          label: '现金',
          value: '现金'
        },
        {
          label: '银行存款',
          value: '银行存款'
        },
        {
          label: '预付',
          value: '预付'
        }
      ],
      // 编辑序列号弹框
      editSerialDialog: false,
      serialId: '',
      serialList: {},
    }
  },
  created() {
    this.role = parseInt(localStorage.getItem('role'))
    if (this.role === 3 || this.role === 5) {
      this.expandAll = true
      this.pager.pageSize = 3
    }
    this.getOrderPage()
  },
  methods: {
    // 获取客户订单分页列表
    async getOrderPage() {
      let params = {
        page: this.pager.currPage,
        pageSize: this.pager.pageSize,
        start_date: this.searchData.start_date,
        end_date: this.searchData.end_date,
        customer: this.searchData.customer,
        js: this.searchData.js,
        model: this.searchData.model
      }
      const { data: result } = await this.$http.get('/order', { params: params })
      this.loading = false
      if (result.status !== 200) return this.$message.error(result.msg)
      this.orderList = result.data
      this.pager = result.pager
    },
    // 搜索
    search() {
      this.pager.currPage = 1
      this.orderList = []
      if (this.rangedDate != null) {
        this.searchData.start_date = this.rangedDate[0]
        this.searchData.end_date = this.rangedDate[1]
      } else {
        this.searchData.start_date = ''
        this.searchData.end_date = ''
      }
      this.getOrderPage()
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(pageSize) {
      this.pager.pageSize = pageSize
      this.getOrderPage()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(currPage) {
      this.pager.currPage = currPage
      this.getOrderPage()
    },
    // 行颜色
    tableRowClassName({ row, rowIndex }) {
      return row.color
    },
    // 清空
    clear() {
      this.rangedDate = null
      this.searchData = {
        start_date: '',
        end_date: '',
        customer: '',
        model: '',
        js: ''
      }
      this.orderList = []
      this.getOrderPage()
    },
    // 新增按钮
    goAddPage() {
      this.$router.push('/order-save')
    },
    load(tree, treeNode, resolve) {
      setTimeout(() => {
        resolve(tree.children)
      }, 50)
    },
    // 打印
    handlePrint(order_id) {
      this.$router.push({
        name: 'print-order',
        params: { order_id: order_id }
      })
    },
    // 新增
    handleSave(order_id) {
      this.$router.push({
        name: 'order-save',
        params: { order_id: order_id }
      })
    },
    // 编辑
    handleEdit(id) {
      this.$router.push({
        name: 'order-update',
        params: { id: id }
      })
    },
    // 编辑序列号
    handleEditSerial(id) {
      this.editSerialDialog = true
      this.serialId = id
      this.getSerialList()
    },
    handleSerialClose() {
      this.editSerialDialog = false
      this.serialId = ''
      this.serialList = {}
    },
    async getSerialList() {
      const { data: result } = await this.$http.get('/serial/' + this.serialId)
      if (result.status !== 200) return this.$message.error(result.msg)
      this.serialList = result.data
    },
    addSerial() {
      if (this.serialList.serial.length < this.serialList.amoumt) {
        this.serialList.serial.push({'serial_number': ''})
      }
    },
    deleteSerial(index, rows) {
      rows.splice(index, 1);
    },
    async submitSerial() {
      const { data: result } = await this.$http.put('/serial/' + this.serialId, {"data": this.serialList.serial})
      if (result.status !== 200) {
          return this.$message.error(result.msg)
      }
      this.$message.success('修改成功！')
      this.handleSerialClose()
    },
    // 删除
    async handleDelete(id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('是否确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        return
      }
      const { data: result } = await this.$http.delete('order/' + id)
      if (result.status !== 200) {
        return this.$message.error(result.msg)
      }
      this.orderList = []
      this.getOrderPage()
      this.$message.success('删除成功！')
    },
    // 打开弹框
    async openBox(order_id, type) {
      const content = type ? '是否确认出库?' : '是否确认撤销出库?'
      const confirmResult = await this.$confirm(content, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return
      }
      if (type) {
        const { data: result } = await this.$http.put('order-confirm', { oid: order_id })
        if (result.status !== 200) {
          return this.$message.error(result.msg)
        }
      } else {
        const { data: result } = await this.$http.put('order-cancel', { oid: order_id })
        if (result.status !== 200) {
          return this.$message.error(result.msg)
        }
      }
      this.orderList = []
      this.getOrderPage()
      this.$message.success('修改成功！')
    },
    // 打开回款弹框
    async repayment(id, type) {
      const content = type % 2 !== 0 ? '是否确认回款?' : '是否确认撤销回款?'
      const confirmResult = await this.$confirm(content, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return
      }
      if (type === 1) {
        const { data: result } = await this.$http.put('order-repay-confirm', { oid: id })
        if (result.status !== 200) {
          return this.$message.error(result.msg)
        }
      } else if (type === 2) {
        const { data: result } = await this.$http.put('order-repay-cancel', { oid: id })
        if (result.status !== 200) {
          return this.$message.error(result.msg)
        }
      } else if (type === 3) {
        const { data: result } = await this.$http.put('order-repay-confirm', { id: id })
        if (result.status !== 200) {
          return this.$message.error(result.msg)
        }
      } else if (type === 4) {
        const { data: result } = await this.$http.put('order-repay-cancel', { id: id })
        if (result.status !== 200) {
          return this.$message.error(result.msg)
        }
      }
      this.orderList = []
      this.getOrderPage()
      this.$message.success('修改成功！')
    },
    // 详情
    handleDetail(order_id) {
      this.$router.push({
        name: 'order-detail',
        params: { order_id: order_id }
      })
    }
  }
}
</script>
<style lang="less">
.query {
  margin-bottom: 20px;
}
.el-select {
  width: 100%;
}
.el-date-editor {
  width: 100%;
}
.el-table .yellow {
  background: #fdf5e6 !important;
}
// .el-table .blue {
//   background: #eef3fb;
// }
// .el-table .green {
//   background: #f0f9eb;
// }
</style>
